﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Shared.Method
{

    public class TelnetByte
    {
        //保存TELNET的信息和意义
        /// <summary>
        /// TELNET头，表示一个指令的开始
        /// </summary>
        public const byte IAC = 255;
        /// <summary>
        /// 希望接收方激活选项
        /// </summary>
        public const byte DO = 253;
        /// <summary>
        /// 希望接收方禁止选项
        /// </summary>
        public const byte DONT = 254;
        /// <summary>
        /// 发送方本身激活选项
        /// </summary>
        public const byte WILL = 251;
        /// <summary>
        /// 发送方本身禁止选项
        /// </summary>
        public const byte WONT = 252;
        /// <summary>
        /// 子选项开始
        /// </summary>
        public const byte SB = 250;
        /// <summary>
        /// 子选项结束
        /// </summary>
        public const byte SE = 240;

        public const byte IS = 48;
        public const byte SEND = 49;
        public const byte INFO = 50;

        /// <summary>
        /// 回车
        /// </summary>
        public const byte CR = 13;
        /// <summary>
        /// 换行
        /// </summary>
        public const byte LF = 10;

        //子选项代码
        /// <summary>
        /// 回显
        /// </summary>
        public const byte ECHO = 1;
        /// <summary>
        /// 终止协商
        /// </summary>
        public const byte SUPPRESS = 3;
        /// <summary>
        /// TELNET状态
        /// </summary>
        public const byte STATUS = 5;
        /// <summary>
        /// 终端类型
        /// </summary>
        public const byte TERMINAL_TYPE = 24;
        /// <summary>
        /// 终端速度
        /// </summary>
        public const byte TERMINAL_SPEED = 32;
        /// <summary>
        /// 流量控制
        /// </summary>
        public const byte FLOW_CONTROL = 33;
        /// <summary>
        /// 显示位置
        /// </summary>
        public const byte DISPLAY_LOCATION = 35;
        /// <summary>
        /// 新环境选择
        /// </summary>
        public const byte NEW_ENVIRONMENT_OPTION = 39;
        /// <summary>
        /// 窗口大小
        /// </summary>
        public const byte WINDOWS_SIZE = 31;
        /// <summary>
        /// 空字符串
        /// </summary>
        public const byte ZERO = 0x00;
    }
    /// <summary>
    /// 升级版本的telnet，使用发送应答模式
    /// </summary>
    public class YcdTelnetSecond
    {
        /*此类将修改telnet模式
         * 从多线程模式改为单线程 发送应答模式
         * 将BYTE转换CHAR的内容尽量缩减
         * 节约处理器负载，提高速度
         * 此类集成了基础连接类
         * */

        private const int PACKET_SIZE = 65535;
        private byte[] _saveRecv = null;

        //服务端IP和端口
        private string _serverAddress = null;
        private int _serverPort = 0;

        //源IP和端口
        private string _sourceAdrress = null;
        private int _sourcePort = 0;

        //客户端
        private TcpClient _client = null;
        //接收线程
        private Task _recvTask = null;

        public YcdTelnetSecond(string serverIp, string sourceIp, int sourcePort, int serverPort = 23)
        {
            _serverAddress = serverIp;
            _serverPort = serverPort;

            _sourceAdrress = sourceIp;
            _sourcePort = sourcePort;
        }

        public bool Connect()
        {
            try
            {
                IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(_sourceAdrress), _sourcePort++);
                _client = new TcpClient(localEP);
                _client.Connect(_serverAddress, _serverPort);

                //RecvByte(_client.GetStream());

                //telnet，send AND receive
                bool telnetRet = TelnetControlCheck();

                return telnetRet;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("YcdTelnetSecond Connect", "连接错误", ex.ToString());
                return false;
            }
        }

        public void Close()
        {
            _client?.Close();
        }

        public bool Connected
        {
            get
            {
                if (_client == null) return false;
                return _client.Connected;
            }
        }
        //public bool Connected()
        //{
        //    if (_client == null) return false;
        //    return _client.Connected;
        //}

        public bool SendAndRecv(string cmdStr, string keyStr, out string allMsg, int waitMiniSecond = 3000)
        {
            allMsg = "";

            if (_client == null || _client.Connected == false) return false;

            //if (PingBaseClass.PingTest(_sourceAdrress, _serverAddress) == false) return false;

            try
            {
                if (cmdStr != null && cmdStr.Contains("flash") && cmdStr.Contains("set"))
                {
                    var splits = cmdStr.Trim().Split(' ');
                    if (splits.Length == 4)
                    {
                        cmdStr = string.Format("{0} {1} {2} '{3}'", splits[0], splits[1], splits[2], splits[3]);
                    }
                }

                if (string.IsNullOrEmpty(cmdStr) == false)
                {
                    Send(Encoding.UTF8.GetBytes(cmdStr));
                    Send(Encoding.UTF8.GetBytes("\r\n"));
                }

                var stream = _client.GetStream();

                bool hasKey = false;
                int times = 0;

                while (times < 100)
                {
                    if (_saveRecv != null)
                        allMsg += Encoding.UTF8.GetString(_saveRecv);//可能协商过程中产生了相应的返回值

                    _saveRecv = null;

                    if (allMsg.ToUpper().Contains(keyStr.ToUpper()))
                    {
                        hasKey = true;
                        break;
                    }

                    if (RecvByte(stream, waitMiniSecond) == false) { break; }//如果正在接受数据当中，则停止当前的循环

                    if (_saveRecv == null) break;//没有接收的数据停止

                    //Thread.Sleep(300);
                    times++;
                }

                allMsg += "\r\n";

                return hasKey;
            }
            catch (Exception ex)
            {
                allMsg = ex.ToString();
                return false;
            }
        }

        /// <summary>
        /// 专门处理接收数据的方法
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        private bool RecvByte(NetworkStream stream,int waitMiniSecond=3000)
        {
            //if (_client.Connected == false) return false;

            if (_recvTask == null || _recvTask.Status == TaskStatus.RanToCompletion)

                _recvTask = Task.Factory.StartNew(() =>
                  {
                      try
                      {
                          _saveRecv = null;

                          byte[] recv = new byte[PACKET_SIZE];

                          int length = 0;

                          //Task.Factory.StartNew();
                          length = stream.Read(recv, 0, PACKET_SIZE);

                          if (length == 0)
                          {
                              _saveRecv = null;
                              throw new Exception("获取数据失败");
                              //return;
                          }

                          var recvList = new List<byte>();

                          //将\r\n转换成\r\n，解决LINUX于WINDOWS的差距
                          for (int i = 0; i < length; i++)
                          {
                              switch (recv[i])
                              {
                                  case TelnetByte.CR:
                                      recvList.Add(TelnetByte.CR);
                                      recvList.Add(TelnetByte.LF);
                                      break;
                                  case TelnetByte.LF:
                                      break;
                                  default:
                                      recvList.Add(recv[i]);
                                      break;
                              }
                          }

                          _saveRecv = recvList.ToArray();
                      }
                      catch (Exception ex)
                      {
                          LogHelper.WriteErrLogTxt("RecvByte()", "收数据失败", ex.ToString());
                          Send("exit");
                          _client?.Close();
                      }
                  });

            _recvTask.Wait(waitMiniSecond);

            //等待N秒，如果进程还在运行当中，则返回FALSE
            if (_recvTask.Status == TaskStatus.RanToCompletion) return true;
            else return false;
        }

        private bool TelnetControlCheck()
        {
            try
            {
                //接收的流
                var stream = _client.GetStream();

                //bool received = true;
                int i = 0;
                for (; i < 10; i++)
                {
                    if (RecvByte(stream) == false) break;
                    if (_saveRecv == null) break;//没有接收的数据停止
                    if (_saveRecv.Contains(TelnetByte.IAC) == false) break;//没有指令结束

                    ProcessOptions(_saveRecv);
                }
                if (i >= 10) return false;//如果通讯十次都没有OK，则返回FALSE
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("接收数据错误，方法TelnetControlCheck()", "RECV ERROR", ex.ToString());
                return false;
            }
        }
        /// <summary>
        /// 处理指令的方法
        /// </summary>
        /// <param name="_saveRecv"></param>
        /// <returns></returns>
        private void ProcessOptions(byte[] saveRecv)
        {
            try
            {
                List<byte[]> listCmd = new List<byte[]>();//保存TELNET指令

                for (int i = 0; i < saveRecv.Length; )
                {
                    if (saveRecv[i] == TelnetByte.IAC && i < saveRecv.Length - 2)//确保数据多余3个
                    {
                        if (saveRecv[i + 1] == TelnetByte.DO
                            || saveRecv[i + 1] == TelnetByte.DONT
                            || saveRecv[i + 1] == TelnetByte.WILL
                            || saveRecv[i + 1] == TelnetByte.WONT)
                        {
                            byte[] cmd = saveRecv.Skip(i).Take(3).ToArray();
                            listCmd.Add(cmd);

                            i = i + 3;//将I移动到2位之后
                        }
                        else if (saveRecv[i + 1] == TelnetByte.SB)
                        {
                            int indexSE = 0;
                            for (int j = i + 1; j < saveRecv.Length; j++)//找到SE的位置
                            {
                                if (saveRecv[j] == TelnetByte.SE)
                                {
                                    indexSE = j;
                                    break;
                                }
                            }

                            if (indexSE == 0) { LogHelper.WriteErrLogTxt("获取SE失败,ProcessOptions()", "TELNET SECOND FAIL", "获取SE结尾字符失败"); return; }

                            byte[] cmd = saveRecv.Skip(i).Take(indexSE - i + 1).ToArray();
                            listCmd.Add(cmd);

                            i = indexSE + 1;
                        }
                    }
                    else break;
                }

                if (listCmd.Count > 0)//做信息反馈
                {
                    byte[] sendMsg = null;
                    for (int i = 0; i < listCmd.Count; i++)
                    {
                        if (sendMsg == null)
                        {
                            sendMsg = ArrangReplay(listCmd[i]);
                        }
                        else
                        {
                            sendMsg = sendMsg.Concat(ArrangReplay(listCmd[i])).ToArray();
                        }
                    }

                    if (sendMsg != null)
                        Send(sendMsg);
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("获取SE失败,ProcessOptions()", "TELNET SECOND FAIL", ex.ToString());
            }
        }
        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="sendMsg"></param>
        public void Send(byte[] sendMsg)
        {
            try
            {
                if (_client.Connected)
                {
                    NetworkStream stream = _client.GetStream();
                    stream.Write(sendMsg, 0, sendMsg.Length);
                    Thread.Sleep(200);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("TelnetSend()", "TelnetSecond ERROR", ex.ToString());
            }
        }

        public void Send(string sendMsg)
        {
            try
            {
                if (_client.Connected)
                {
                    sendMsg += "\r\n";
                    NetworkStream stream = _client.GetStream();
                    stream.Write(Encoding.UTF8.GetBytes(sendMsg), 0, sendMsg.Length);
                    Thread.Sleep(200);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("TelnetSend(string)", "TelnetSecond ERROR", ex.ToString());
            }
        }

        private byte[] ArrangReplay(byte[] cmd)
        {
            try
            {
                if (cmd.Length < 3) return null;

                byte Verb = cmd[1];
                byte Option = cmd[2];
                bool bDefined = false;

                if (Option == TelnetByte.ECHO || Option == TelnetByte.SUPPRESS)
                {
                    bDefined = true;
                }

                List<byte> replay = new List<byte>();
                replay.Add(TelnetByte.IAC);

                if (bDefined)
                {
                    if (Verb == TelnetByte.DO)
                    {
                        replay.Add(TelnetByte.WILL);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.DONT)
                    {
                        replay.Add(TelnetByte.WONT);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.WILL)
                    {
                        replay.Add(TelnetByte.DO);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.WONT)
                    {
                        replay.Add(TelnetByte.DONT);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.SB)
                    {
                        var Modifier = cmd[3];
                        if (Modifier == TelnetByte.SEND)
                        {
                            replay.Add(TelnetByte.SB);
                            replay.Add(Option);
                            replay.Add(TelnetByte.IS);
                            replay.Add(TelnetByte.IAC);
                            replay.Add(TelnetByte.SE);
                        }
                    }
                }
                else
                {
                    if (Verb == TelnetByte.DO)
                    {
                        replay.Add(TelnetByte.WONT);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.DONT)
                    {
                        replay.Add(TelnetByte.WONT);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.WILL)
                    {
                        replay.Add(TelnetByte.DONT);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.WONT)
                    {
                        replay.Add(TelnetByte.DONT);
                        replay.Add(Option);
                    }
                }

                return replay.ToArray();
            }
            catch
            {
                return null;
            }
        }
    }

    public class YcdTelnetMethod
    {
        private static List<string> listPort = null;

        public static bool CheckPortSpeed(YcdTelnetSecond tel, out string message)
        {
            message = string.Empty;
            try
            {
                GetPorts();

                if (listPort.Count == 0) return true;

                string msg = string.Empty;

                bool checkRet = false;
                for (int i = 0; i < listPort.Count; i++)
                {
                    checkRet = CheckPortSpeed(tel, out msg, listPort[i]);

                    message += msg;

                    if (checkRet == false) break;
                }

                return checkRet;
            }
            catch (Exception ex)
            {
                message = ex.ToString();

                return false;
            }
        }

        private static void GetPorts()
        {
            int portNum = 0;
            if (listPort == null//只有最开始的时候才需要加载数据
                && int.TryParse(AppSetting.GetValue("PortTestNum"), out portNum))
            {
                listPort = new List<string>();
                for (int i = 1; i <= portNum; i++)
                {
                    var port = AppSetting.GetValue("Port" + i);
                    if (string.IsNullOrEmpty(port) == false
                        && listPort.Contains(port) == false) listPort.Add(port);
                }
            }
        }

        public static bool CheckPortSpeed(YcdTelnetSecond tel, out string msg, string port)
        {
            msg = "";

            if (tel == null || tel.Connected == false) return false;

            if (tel.SendAndRecv("diag port get status port " + port, "command", out msg) == false)
            {
                return false;
            }

            switch (port)
            {
                case "0":
                case "1":
                case "2":
                case "3":
                    if (msg.Contains("100M") && msg.Contains("Up")) return true;
                    else return false;
                case "4":
                    if (msg.Contains("1000M") && msg.Contains("Up")) return true;
                    else return false;
                default:
                    return false;
            }
        }

        //public static bool CheckPortSpeed(YcdTelnetSecond tel, out string msg)
        //{
        //    msg = "";

        //    if (tel == null || tel.Connected == false) return false;

        //    if (tel.SendAndRecv("diag port get status port all", "command", out msg) == false)
        //    {
        //        return false;
        //    }

        //    var speeds = msg.Replace("\n", "").Split('\r');//分隔字符串
        //    var upSpeed = (from s in speeds
        //                   where s.Contains("Up")
        //                   select s).ToList();//找到连接的端口

        //    if (upSpeed == null || upSpeed.Count == 0) return false;

        //    for (int i = 0; i < upSpeed.Count; i++)
        //    {
        //        if (upSpeed[i].Contains("4") && upSpeed[i].Contains("1000M") == false) return false;
        //        if ((upSpeed[i].Contains("1") || upSpeed[i].Contains("2") || upSpeed[i].Contains("3")|| upSpeed[i].Contains("0"))
        //            && upSpeed[i].Contains("100M") == false) return false;
        //    }

        //    return true;
        //}

        public static YcdTelnetSecond TelnetModem(string sourceIp,string destIp,int sourcePort,int destPort = 23,string name="admin",string password="1234")
        {
            YcdTelnetSecond telnet = new YcdTelnetSecond(destIp, sourceIp, sourcePort,destPort);
            if (telnet.Connect() == false)
            {
                //AppendRichTextBox("配置TELNET通讯过程失败");
                telnet.Send("exit");
                telnet.Close();
                return null;
            }

            //System.Threading.Thread.Sleep(2000);

            string msg;

            bool telRet = false;

            if (telnet.SendAndRecv(string.Empty, "login", out msg))
            {
                //AppendRichTextBox("输入用户名称……");
                if (telnet.SendAndRecv(name, "password", out msg))
                {
                    //AppendRichTextBox("输入用户密码……");
                    if (telnet.SendAndRecv(password, "#", out msg))
                    {
                        //AppendRichTextBox("登录成功");
                        telRet = true;
                    }
                }
            }

            if (telRet == false)
            {
                //AppendRichTextBox("登录失败");
                telnet.Send("exit");
                telnet.Close();
                return null;
            }

            //AppendRichTextBox(msg);

            return telnet;
        }

        //public static bool CheckPortSpeed(string msg)
        //{
        //    var speeds = msg.Replace("\n", "").Split('\r');//分隔字符串
        //    var upSpeed = (from s in speeds
        //                   where s.Contains("Up")
        //                   select s).ToList();//找到连接的端口

        //    if (upSpeed == null || upSpeed.Count == 0) return false;

        //    for (int i = 0; i < upSpeed.Count; i++)
        //    {
        //        if (upSpeed.Contains("4") && upSpeed.Contains("1000M") == false) return false;
        //        if ((upSpeed.Contains("1") || upSpeed.Contains("2") || upSpeed.Contains("3"))
        //            && upSpeed.Contains("100M") == false) return false;
        //    }

        //    return true;
        //}
    }


    public class YcdTelnetThird
    {
        private const int PACKET_SIZE = 65535;
        //private byte[] _saveRecv = null;

        //服务端IP和端口
        private string _serverAddress = null;
        private int _serverPort = 0;

        //源IP和端口
        private string _sourceAdrress = null;
        private int _sourcePort = 0;

        //客户端
        private TcpClient _client = null;

        //private Task _recvTask = null;

        public event Action<string> OnReceive;

        private bool _record = false;
        private StringBuilder _recordMsg = new StringBuilder();

        public YcdTelnetThird(string serverIp, string sourceIp, int sourcePort, int serverPort = 23)
        {
            _serverAddress = serverIp;
            _serverPort = serverPort;

            _sourceAdrress = sourceIp;
            _sourcePort = sourcePort;
        }

        public bool Connect()
        {
            try
            {
                IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(_sourceAdrress), _sourcePort++);
                _client = new TcpClient(localEP);
                _client.Connect(_serverAddress, _serverPort);

                //bool telnetRet = TelnetControlCheck();
                RunRecvMsg();

                //Thread.Sleep(1000);

                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("YcdTelnetSecond Connect", "连接错误", ex.ToString());
                return false;
            }
        }

        private void RunRecvMsg()
        {
            Task.Run(() =>
            {

                if (Connected == false) return;

                var stream = _client.GetStream();

                byte[] recv = new byte[PACKET_SIZE];

                try
                {
                    while (true)
                    {
                        Task<int> length = stream.ReadAsync(recv, 0, PACKET_SIZE);
                        if (length.Result <= 0) break;

                        string recvMsg = Encoding.UTF8.GetString(recv, 0, length.Result);

                        if (recv.Contains(TelnetByte.IAC)) ProcessOptions(recv);
                        else
                        {
                            OnReceive?.Invoke(recvMsg);

                            if (_record)
                            {
                                _recordMsg.Append(recvMsg.Replace("\0", ""));
                            }
                        }
                    }
                }
                catch
                {

                }
            });
        }

        public void Close()
        {
            _client?.Close();
        }

        public bool Connected
        {
            get
            {
                if (_client == null) return false;
                return _client.Connected;
            }
        }

        private bool TelnetControlCheck()
        {
            try
            {
                //接收的流
                var stream = _client.GetStream();

                byte[] recv = new byte[PACKET_SIZE] ;

                //bool received = true;
                int i = 0;
                for (; i < 10; i++)
                {
                    //_saveRecv=stream.Read()
                    stream.Read(recv, 0, PACKET_SIZE);
                    if (recv == null) break;//没有接收的数据停止
                    if (recv.Contains(TelnetByte.IAC) == false) break;//没有指令结束

                    ProcessOptions(recv);
                }
                if (i >= 10) return false;//如果通讯十次都没有OK，则返回FALSE
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("接收数据错误，方法TelnetControlCheck()", "RECV ERROR", ex.ToString());
                return false;
            }
        }
        /// <summary>
        /// 处理指令的方法
        /// </summary>
        /// <param name="_saveRecv"></param>
        /// <returns></returns>
        private void ProcessOptions(byte[] saveRecv)
        {
            try
            {
                List<byte[]> listCmd = new List<byte[]>();//保存TELNET指令

                for (int i = 0; i < saveRecv.Length;)
                {
                    if (saveRecv[i] == TelnetByte.IAC && i < saveRecv.Length - 2)//确保数据多余3个
                    {
                        if (saveRecv[i + 1] == TelnetByte.DO
                            || saveRecv[i + 1] == TelnetByte.DONT
                            || saveRecv[i + 1] == TelnetByte.WILL
                            || saveRecv[i + 1] == TelnetByte.WONT)
                        {
                            byte[] cmd = saveRecv.Skip(i).Take(3).ToArray();
                            listCmd.Add(cmd);

                            i += 3;//将I移动到2位之后
                        }
                        else if (saveRecv[i + 1] == TelnetByte.SB)
                        {
                            int indexSE = 0;
                            for (int j = i + 1; j < saveRecv.Length; j++)//找到SE的位置
                            {
                                if (saveRecv[j] == TelnetByte.SE)
                                {
                                    indexSE = j;
                                    break;
                                }
                            }

                            if (indexSE == 0) { LogHelper.WriteErrLogTxt("获取SE失败,ProcessOptions()", "TELNET SECOND FAIL", "获取SE结尾字符失败"); return; }

                            byte[] cmd = saveRecv.Skip(i).Take(indexSE - i + 1).ToArray();
                            listCmd.Add(cmd);

                            i = indexSE + 1;
                        }
                    }
                    else break;
                }

                if (listCmd.Count > 0)//做信息反馈
                {
                    byte[] sendMsg = null;
                    for (int i = 0; i < listCmd.Count; i++)
                    {
                        if (sendMsg == null)
                        {
                            sendMsg = ArrangReplay(listCmd[i]);
                        }
                        else
                        {
                            sendMsg = sendMsg.Concat(ArrangReplay(listCmd[i])).ToArray();
                        }
                    }

                    if (sendMsg != null)
                        Send(sendMsg);
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("获取SE失败,ProcessOptions()", "TELNET SECOND FAIL", ex.ToString());
            }
        }

        private byte[] ArrangReplay(byte[] cmd)
        {
            try
            {
                if (cmd.Length < 3) return null;

                byte Verb = cmd[1];
                byte Option = cmd[2];
                bool bDefined = false;

                if (Option == TelnetByte.ECHO || Option == TelnetByte.SUPPRESS)
                {
                    bDefined = true;
                }

                List<byte> replay = new List<byte>();
                replay.Add(TelnetByte.IAC);

                if (bDefined)
                {
                    if (Verb == TelnetByte.DO)
                    {
                        replay.Add(TelnetByte.WILL);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.DONT)
                    {
                        replay.Add(TelnetByte.WONT);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.WILL)
                    {
                        replay.Add(TelnetByte.DO);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.WONT)
                    {
                        replay.Add(TelnetByte.DONT);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.SB)
                    {
                        var Modifier = cmd[3];
                        if (Modifier == TelnetByte.SEND)
                        {
                            replay.Add(TelnetByte.SB);
                            replay.Add(Option);
                            replay.Add(TelnetByte.IS);
                            replay.Add(TelnetByte.IAC);
                            replay.Add(TelnetByte.SE);
                        }
                    }
                }
                else
                {
                    if (Verb == TelnetByte.DO)
                    {
                        replay.Add(TelnetByte.WONT);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.DONT)
                    {
                        replay.Add(TelnetByte.WONT);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.WILL)
                    {
                        replay.Add(TelnetByte.DONT);
                        replay.Add(Option);
                    }
                    else if (Verb == TelnetByte.WONT)
                    {
                        replay.Add(TelnetByte.DONT);
                        replay.Add(Option);
                    }
                }

                return replay.ToArray();
            }
            catch
            {
                return null;
            }
        }

        public void Send(byte[] sendMsg)
        {
            try
            {
                if (_client.Connected)
                {
                    NetworkStream stream = _client.GetStream();
                    stream.WriteAsync(sendMsg, 0, sendMsg.Length);
                    Thread.Sleep(8);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("TelnetSend()", "TelnetSecond ERROR", ex.ToString());
            }
        }

        public void Send(string sendMsg)
        {
            try
            {
                if (_client.Connected)
                {
                    sendMsg += "\r\n";
                    NetworkStream stream = _client.GetStream();
                    stream.WriteAsync(Encoding.UTF8.GetBytes(sendMsg), 0, sendMsg.Length);
                    Thread.Sleep(8);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("TelnetSend(string)", "TelnetThirdERROR", ex.ToString());
            }
        }

        public void SetRecord()
        {
            _record = true;
            _recordMsg.Clear();
        }

        public void SetNotRecord()
        {
            _record = false;
        }

        public string GetRecordStr()
        {
            if (_record) return _recordMsg.ToString();
            else return string.Empty;
        }

    }
}
